<script lang="tsx" setup>
import { reactive, ref, watch } from 'vue';
import { useNaiveForm } from '@/hooks/common/form';
import { resetPassword } from '@/service/api/system/user';
import type { UserPassword } from '@/service/types/system';
defineOptions({
  name: 'RestPassword'
});
type Model = {
  password: string | '';
};
const tableConstatns = ['default', 'customer'];
const tabVal = ref<string>(tableConstatns[0]);
type RuleKey = Extract<keyof Model, 'password'>;
const { formRef, validate, restoreValidation } = useNaiveForm();
const submitLoading = ref<boolean>(false);
// const { createRequiredRule } = useFormRules();

const visible = defineModel<boolean>('visible', {
  default: false
});
const rules: Record<RuleKey, App.Global.FormRule> = {
  password: {
    required: true,
    pattern: /^\w{6,18}$/,
    message: '密码格式不正确，6-18位字符，包含字母、数字、下划线',
    trigger: 'blur'
  }
};
const initDefualtModal = (): Model => {
  return {
    password: ''
  };
};
const model: Model = reactive(initDefualtModal());

interface Props {
  currentRowId: number | string | undefined;
}
const props = defineProps<Props>();
function closeResetPasswordModal() {
  visible.value = false;
}

const handleUpdateValue = (value: string) => {
  tabVal.value = value;
};

const handleDefualtPassword = () => {
  submitLoading.value = true;
  resetPassword(tableConstatns[0], {
    userId: props.currentRowId
  } as UserPassword).then(res => {
    submitLoading.value = false;
    if (!res?.error) {
      // console.log(res);
      visible.value = false;
      window.$message.success(res?.data?.msg);
    }
  });
};
const handleCustomerPassword = async () => {
  // console.log('自定义密码');
  await validate();
  const { ...params } = model;
  submitLoading.value = true;
  resetPassword(tableConstatns[1], {
    userId: props.currentRowId,
    password: params.password
  } as UserPassword).then(res => {
    submitLoading.value = false;
    if (!res?.error) {
      // console.log(res);
      visible.value = false;
      window.$message.success(res?.data?.msg);
    }
  });
  // console.log('params: ', params);
};

const hdnleSubmit = () => {
  if (tabVal.value === tableConstatns[0]) {
    // 默认的
    handleDefualtPassword();
  } else {
    handleCustomerPassword();
  }
};

watch(visible, () => {
  if (visible.value) {
    restoreValidation();
  }
});
</script>

<template>
  <div>
    <NModal v-model:show="visible" title="重置密码" preset="card" class="w-400px">
      <NTabs type="segment" animated :value="tabVal" @update:value="handleUpdateValue">
        <NTabPane :name="tableConstatns[0]" tab="默认密码">
          <NAlert :show-icon="false">重置为系统默认的初始密码</NAlert>
        </NTabPane>
        <NTabPane :name="tableConstatns[1]" tab="自定义">
          <NForm ref="formRef" :model="model" :rules="rules" label-placement="top">
            <NFormItem label="自定义密码" path="password">
              <NInput v-model:value="model.password" clearable type="password" placeholder="密码" />
            </NFormItem>
          </NForm>
        </NTabPane>
      </NTabs>
      <template #footer>
        <NSpace justify="end" :size="16">
          <NButton @click="closeResetPasswordModal">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitLoading" :disabled="submitLoading" @click="hdnleSubmit">
            {{ $t('common.confirm') }}
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style lang="scss" scoped></style>
